﻿using Activity.Data;
using Activity.Helper;
using Activity.Message;
using Activity.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Activity.Helper.OAuthHelper;

namespace Activity.API
{
   public class WeixinApi: BaseAPICommand
    {
        public override HttpMethod RequestType
        {
            get
            {
                return HttpMethod.GET; 
            }
        }

        public string OpenID { get; protected set; }
        public override string Url
        {
            get
            {
                //string url = string.Format(WeiXinConst.WeiXin_User_GetInfoUrl, AccessToken.GetAccssTokenFromCacheServer(), this.OpenID);
                //return url;
                return "";
            }
        }

        /// <summary>
        /// 通过code换取网页授权access_token
        /// 这里通过code换取的是一个特殊的网页授权access_token,与基础支持中的access_token
        /// （该access_token用于调用其他接口）不同。公众号可通过下述接口来获取网页授权access_token。
        /// 如果网页授权的作用域为snsapi_base，则本步骤中获取到网页授权access_token的同时，
        /// 也获取到了openid，snsapi_base式的网页授权流程即到此为止。
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static Oauth2AccessToken GetOpenID(string code = "")
        {
            var result = WeiXinHelper.GetOauth2AccessToken(code);
            Log.WriteLog($"通过Code:{code},获取openID{result.openid}");
            return result;
        }
       
        public static int GetAccessToken(string openId)
        {
            //var rc = new RedisClient(10);
            //var result = "";
            //if (rc.KeyExists("BC_Access_Token"))
            //{
            //    result= rc.GetString("BC_Access_Token");
            //}
            //else
            //{
            //    var token = WeiXinHelper.GetAccessToken();
            //    rc.SetString("BC_Access_Token", token, 120);
            //    result = token;
            //}
            var token = WeiXinHelper.GetAccessToken();
            var userInfo = WeiXinHelper.GetUserInfo(openId, token);

            return (int)userInfo?.Subscribe;
        }
        /// <summary>
        /// 根据code获取用户详细信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static string GetOauth2User(string code)
        {
            var user = WeiXinHelper.GetOauth2UserInfo(code);
            if (user == null)
            {
                Log.Error("获取用户信息失败！");
                return "";
            }
            var dc = new ActivityEntities();
            if (dc.Bas_WeixinUser.Any(t => t.openid == user.openid))
            {
                return user.openid;
            }
            var adduser = new Bas_WeixinUser{
                openid = user.openid,
                sex = user.sex,
                province = user.province,
                city = user.city,
                weixinName = user.nickname,
                imgurl = user.headimgurl,
                country = user.country,
                CreateDate = DateTime.Now
            };
            try
            {
                dc.Bas_WeixinUser.Add(adduser);
                dc.SaveChanges();
                return user.openid;
            }catch(Exception ex)
            {
                Log.Error("添加用户详细信息出错："+ex.Message);
                return "";
            }
        }

        /// <summary>
        ///获取用户基本信息 
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static WeiXinUserInfo GetUserInfo(string openId)
        {
            var dc = new ActivityEntities();
            var query = dc.Bas_WeixinUser.FirstOrDefault(t => t.openid == openId);
            if (query == null)
            {
                var token = WeiXinHelper.GetAccessToken();
                var result = WeiXinHelper.GetUserInfo(openId, token);
                if (result != null)
                {
                    var adduser = new Bas_WeixinUser
                    {
                        openid = result.OpenId,
                        sex = result.Sex,
                        province = result.Province,
                        city = result.City,
                        weixinName = result.NickName,
                        imgurl = result.HeadImgUrl,
                        country = result.Country,
                        CreateDate = DateTime.Now
                    };
                    try
                    {
                        dc.Bas_WeixinUser.Add(adduser);
                        dc.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        Log.Error("添加用户详细信息出错：" + ex.Message);
                    }
                }
                return result;
            }
            else
            {
                return new WeiXinUserInfo
                {
                    NickName = query.weixinName,
                    OpenId = query.openid,
                    City = query.city,
                    Country = query.country,
                    HeadImgUrl = query.imgurl,
                    Province = query.province,
                    Sex = query.sex
                };
            }
        }
    }
}
